package com.mo.controller;


import com.mo.entity.Category;
import com.mo.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 分类 前端控制器
 * </p>
 *
 * @author mo
 * @since 2022-08-27
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private ICategoryService categoryService;

    @GetMapping("/categories")
    public List<Category> selectAll() {
        return categoryService.selectAllCate();
    }


    @PatchMapping("/categories/{id}")
    public Category updateCategory(@PathVariable("id") Integer id,
                                   @RequestBody Category category) {
        category.setId(id);
        category.setUpdatedAt(LocalDateTime.now());
        //把系统当前时间作为该属性的值
        categoryService.updateById(category);
        return category;
    }

    @PostMapping("/categories")
    public Category add(@RequestBody Category category) {
        category.setCreatedAt(LocalDateTime.now());
        category.setUpdatedAt(LocalDateTime.now());
        categoryService.save(category);
        return category;
    }

    @DeleteMapping("/categories/{id}")
    public void deleteById(@PathVariable int id) {
        try {
            categoryService.removeById(id);
        } catch (Exception e) {
            throw new RuntimeException("类别下面有关联数据，删除异常");
        }
    }

    @GetMapping("selectOne")
    public Category selectOne(Integer id) {
        return categoryService.getById(id);
    }
}

